#!/usr/bin/env python

import os
from pygments import highlight
from pygments.lexers import get_lexer_for_mimetype
from pygments.formatters import HtmlFormatter

from app.commits import Commits


class Revisions:
  @staticmethod
  def list(repo, date=None):
    """Last revisions with date and hexsha"""
    revs = []
    for c in repo.iter_commits(max_count=100):
      timestamp = c.authored_date - c.author_tz_offset
      revs.append([c.hexsha, timestamp])
      
    return revs
    
  @staticmethod
  def navigate_path(tree, path):
    """Go through tree with given path"""
    try:
      path = str(path).split("/")
      path = filter(lambda p: p != "", path)
      for node in path:
        tree = tree[node]
    except KeyError:
      return None
    
    return tree
    
  @staticmethod
  def list_folder(tree):
    """Return all folders and files in this node."""
    data = []
    
    print "================", tree
    print "================", dir(tree)
    
    for node in tree:
      # Bypass bug in GitPython
      try:
        node.name
      except:
        continue
      
      # Skip hidden files
      if node.name[0] is not ".":
        data.append({
          "name": node.name,
          "is_file": node.type != "tree"
        })
      
    return Revisions.htmldir(tree.path, data)
    
  @staticmethod
  def htmldir(parent, nodes):
    html = ['<ul class="jqueryFileTree" style="">']
    
    for n in nodes:
      name = n["name"]
      path = parent + "/" + name
      
      if n["is_file"]:
        ext = os.path.splitext(name)[1][1:] # get .ext and remove dot
        html.append('<li class="file ext_%s"><a href="#" rel="%s">%s</a></li>' % (ext, path, name))
      else:
        html.append('<li class="directory collapsed"><a href="#" rel="%s/">%s</a></li>' % (path, name))
     
    html.append('</ul>')
    return ''.join(html)
  
  @staticmethod
  def show_file(blob):
    """Return syntax highlighted content of file."""
    code = blob.data_stream.read()
    lexer = get_lexer_for_mimetype(blob.mime_type)
    return highlight(code, lexer, HtmlFormatter())
  